package com.leap.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leap.entity.*;
import com.leap.entity.dto.AuthorizeDTO;
import com.leap.mapper.AccountMapper;
import com.leap.mapper.ArticleMapper;
import com.leap.mapper.CommentMapper;
import com.leap.properties.WeChatProperties;
import com.leap.service.*;
import com.leap.utils.HttpClientUtil;
import com.leap.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Autowired
    private  WeChatProperties weChatProperties;

    @Autowired
    private JwtUtils utils;

    @Autowired
    private InteractCommentService interactCommentService;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private AccountCategoryService accountCategoryService;

    @Autowired
    private InteractService interactService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private CommentMapper commentMapper;


    @Override
    public Account wxLogin(String openid) {
        if (openid == null){
            return null;
        }

        Account account = this.selectByOpenId(openid);
        if (account == null){
             account = Account.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            this.saveOrUpdate(account);
        }

        return account;
    }

    @Override
    public Account selectByOpenId(String openid) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);

        Account account = this.getOne(queryWrapper);
        return account;
    }

    @Override
    public UserDetails loadUserByUsername(String openid) throws UsernameNotFoundException {
        Account account = this.wxLogin(openid);
//        if (account == null){
//            throw new UsernameNotFoundException("账号错误");
//        }
        return null;
    }

    @Override
    public Account loadUserById(String openid) {

        Account account = wxLogin(openid);
        if (account == null){
            throw new UsernameNotFoundException("账号错误");
        }

        return account;
    }

    @Override
    public void updateByDTO(AuthorizeDTO authorizeDTO,String headerToken) {
        Long id = utils.getAccountIdByToken(headerToken);

        Account account = Account.builder()
                .id(id)
                .name(authorizeDTO.getName() == null ? null : authorizeDTO.getName())
                .phone(authorizeDTO.getPhone() == null ? null : authorizeDTO.getPhone())
                .sex(authorizeDTO.getSex() == null ? null : authorizeDTO.getSex())
                .avatar(authorizeDTO.getAvatar() == null ? null : authorizeDTO.getAvatar())
                .email(authorizeDTO.getEmail() == null ? null : authorizeDTO.getEmail())
                .birth(authorizeDTO.getBirth() == null ? null : authorizeDTO.getBirth())
                .build();

        this.saveOrUpdate(account);

    }

    @Override
    public AuthorizeDTO getInfoByToken(String headerToken) {
        Long id = utils.getAccountIdByToken(headerToken);

        Account account = accountMapper.selectById(id);
        return AuthorizeDTO.builder()
                .name(account.getName() == null ? null : account.getName())
                .phone(account.getPhone() == null ? null : account.getPhone())
                .sex(account.getSex() == null ? null : account.getSex())
                .avatar(account.getAvatar() == null ? null : account.getAvatar())
                .email(account.getEmail() == null ? null : account.getEmail())
                .birth(account.getBirth() == null ? null : account.getBirth())
                .build();
    }

    @Override
    public Boolean ChangeLikeByArticleId(Long articleId, String headerToken) {
        Long accountId = utils.getAccountIdByToken(headerToken);

        String isLike = accountMapper.isLikeByArticleId(articleId, accountId);
        if (isLike == null){
            accountMapper.insertLike(articleId, accountId,LocalDateTime.now());
            articleMapper.addOneLikeNum(articleId);
            return true;
        }else {
            accountMapper.deleteLike(articleId,accountId);
            articleMapper.minusOneLikeNum(articleId);
            return false;
        }
    }

    @Override
    public Boolean ChangeLikeByCommentId(Long commentId, String headerToken) {
        Long accountId = utils.getAccountIdByToken(headerToken);

        String isLike = accountMapper.isLikeByCommentId(commentId, accountId);
        if (isLike == null){
            accountMapper.insertCommentLike(commentId, accountId,LocalDateTime.now());
            commentMapper.addOneLikeCount(commentId);
            return true;
        }else{
            accountMapper.deleteCommentLike(commentId,accountId);
            commentMapper.minusOneLikeCount(commentId);
            return false;
        }
    }

    @Override
    public void loadCategoryViewCache(Long accountId) {
        //往数据库中加载用户分类浏览次数的集合
        accountCategoryService.getCategoryViewByAccountIdInMySQL(accountId);
    }

    @Override
    public void loadLikeListCache(Long accountId) {
        //从数据库中加载用户喜欢的缓存
        interactService.getInteractListByAccountIdInMQL(accountId);
    }

    @Override
    public void refreshInteractList(Long accountId) {

        //刷新Redis缓存
        interactService.refreshInteractList(accountId);
    }

    @Override
    public void loadCategoryName() {

        //从数据库中加载分类信息
        categoryService.loadCategoryName();

    }

    @Override
    public List<Long> loadCommentLikeList(Long accountId) {

        return interactCommentService.getInteractCommentsByAccountIdInMQL(accountId);
    }



}
